const db = require('../config/database');
const { successResponse, errorResponse } = require('../utils/response');

/**
 * 获取排行榜
 */
const getLeaderboard = async (req, res) => {
    try {
        const { type = 'stars', school, grade, period = 'all', limit = 50 } = req.query;
        
        let query = `
            SELECT 
                u.id,
                u.username,
                u.school,
                u.grade,
                u.avatar,
                u.stars,
                u.total_correct,
                u.total_wrong,
                u.continuous_days,
                ROUND(u.total_correct * 100.0 / NULLIF(u.total_correct + u.total_wrong, 0), 2) as accuracy,
                COUNT(DISTINCT up.word_id) as words_learned,
                p.level as pet_level
            FROM users u
            LEFT JOIN user_progress up ON u.id = up.user_id AND up.mastery_level >= 60
            LEFT JOIN pets p ON u.id = p.user_id
        `;
        
        const params = [];
        const conditions = [];
        
        // 学校筛选
        if (school) {
            conditions.push('u.school = ?');
            params.push(school);
        }
        
        // 年级筛选
        if (grade) {
            conditions.push('u.grade = ?');
            params.push(grade);
        }
        
        if (conditions.length > 0) {
            query += ' WHERE ' + conditions.join(' AND ');
        }
        
        query += ' GROUP BY u.id';
        
        // 排序
        if (type === 'stars') {
            query += ' ORDER BY u.stars DESC';
        } else if (type === 'words') {
            query += ' ORDER BY words_learned DESC';
        } else if (type === 'accuracy') {
            query += ' ORDER BY accuracy DESC';
        } else if (type === 'streak') {
            query += ' ORDER BY u.continuous_days DESC';
        }
        
        const limitNum = Math.min(Math.max(1, parseInt(limit) || 50), 100);
        query += ` LIMIT ${limitNum}`; // 使用字符串拼接避免参数问题
        
        const [leaderboard] = await db.execute(query, params);
        
        // 添加排名
        leaderboard.forEach((item, index) => {
            item.rank = index + 1;
        });
        
        return successResponse(res, leaderboard);
        
    } catch (error) {
        console.error('获取排行榜错误:', error);
        return errorResponse(res, '获取排行榜失败', 500, error);
    }
};

/**
 * 获取用户排名
 */
const getUserRank = async (req, res) => {
    try {
        const userId = req.user.id;
        const { type = 'stars' } = req.query;
        
        // 获取用户信息
        const [users] = await db.execute(
            'SELECT school, grade, stars FROM users WHERE id = ?',
            [userId]
        );
        
        if (users.length === 0) {
            return errorResponse(res, '用户不存在', 404);
        }
        
        const user = users[0];
        
        // 计算全服排名
        let globalRankQuery = `
            SELECT COUNT(*) + 1 as rank
            FROM users u
            WHERE u.${type} > (SELECT ${type} FROM users WHERE id = ?)
        `;
        
        const [globalRank] = await db.execute(globalRankQuery, [userId]);
        
        // 计算学校排名
        const [schoolRank] = await db.execute(
            `SELECT COUNT(*) + 1 as rank
             FROM users u
             WHERE u.school = ? AND u.${type} > (SELECT ${type} FROM users WHERE id = ?)`,
            [user.school, userId]
        );
        
        // 计算年级排名
        const [gradeRank] = await db.execute(
            `SELECT COUNT(*) + 1 as rank
             FROM users u
             WHERE u.grade = ? AND u.${type} > (SELECT ${type} FROM users WHERE id = ?)`,
            [user.grade, userId]
        );
        
        return successResponse(res, {
            globalRank: globalRank[0].rank,
            schoolRank: schoolRank[0].rank,
            gradeRank: gradeRank[0].rank
        });
        
    } catch (error) {
        console.error('获取用户排名错误:', error);
        return errorResponse(res, '获取用户排名失败', 500, error);
    }
};

/**
 * 搜索用户
 */
const searchUsers = async (req, res) => {
    try {
        const { keyword, limit = 20 } = req.query;
        
        if (!keyword || keyword.trim().length === 0) {
            return errorResponse(res, '请输入搜索关键词', 400);
        }
        
        const [users] = await db.execute(
            `SELECT 
                u.id,
                u.username,
                u.school,
                u.grade,
                u.avatar,
                u.stars,
                COUNT(DISTINCT up.word_id) as words_learned
             FROM users u
             LEFT JOIN user_progress up ON u.id = up.user_id
             WHERE u.username LIKE ?
             GROUP BY u.id
             LIMIT ?`,
            [`%${keyword}%`, parseInt(limit)]
        );
        
        return successResponse(res, users);
        
    } catch (error) {
        console.error('搜索用户错误:', error);
        return errorResponse(res, '搜索用户失败', 500, error);
    }
};

/**
 * 添加好友
 */
const addFriend = async (req, res) => {
    try {
        const userId = req.user.id;
        const { friendId } = req.body;
        
        if (!friendId) {
            return errorResponse(res, '请提供好友ID', 400);
        }
        
        if (userId === friendId) {
            return errorResponse(res, '不能添加自己为好友', 400);
        }
        
        // 检查好友是否存在
        const [friends] = await db.execute(
            'SELECT id FROM users WHERE id = ?',
            [friendId]
        );
        
        if (friends.length === 0) {
            return errorResponse(res, '用户不存在', 404);
        }
        
        // 检查是否已经是好友
        const [existing] = await db.execute(
            'SELECT * FROM friendships WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)',
            [userId, friendId, friendId, userId]
        );
        
        if (existing.length > 0) {
            return errorResponse(res, '已经是好友或已发送好友请求', 400);
        }
        
        // 插入好友请求
        await db.execute(
            'INSERT INTO friendships (user_id, friend_id, status) VALUES (?, ?, ?)',
            [userId, friendId, 'pending']
        );
        
        return successResponse(res, null, '好友请求已发送');
        
    } catch (error) {
        console.error('添加好友错误:', error);
        return errorResponse(res, '添加好友失败', 500, error);
    }
};

/**
 * 获取好友列表
 */
const getFriendsList = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const [friends] = await db.execute(
            `SELECT 
                u.id,
                u.username,
                u.school,
                u.grade,
                u.avatar,
                u.stars,
                u.continuous_days,
                f.created_at as friend_since
             FROM friendships f
             INNER JOIN users u ON (
                 CASE 
                     WHEN f.user_id = ? THEN f.friend_id
                     ELSE f.user_id
                 END = u.id
             )
             WHERE (f.user_id = ? OR f.friend_id = ?) AND f.status = 'accepted'
             ORDER BY u.stars DESC`,
            [userId, userId, userId]
        );
        
        return successResponse(res, friends);
        
    } catch (error) {
        console.error('获取好友列表错误:', error);
        return errorResponse(res, '获取好友列表失败', 500, error);
    }
};

/**
 * 获取好友请求
 */
const getFriendRequests = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const [requests] = await db.execute(
            `SELECT 
                f.id as request_id,
                u.id as user_id,
                u.username,
                u.school,
                u.grade,
                u.avatar,
                u.stars,
                f.created_at
             FROM friendships f
             INNER JOIN users u ON f.user_id = u.id
             WHERE f.friend_id = ? AND f.status = 'pending'
             ORDER BY f.created_at DESC`,
            [userId]
        );
        
        return successResponse(res, requests);
        
    } catch (error) {
        console.error('获取好友请求错误:', error);
        return errorResponse(res, '获取好友请求失败', 500, error);
    }
};

/**
 * 处理好友请求
 */
const handleFriendRequest = async (req, res) => {
    try {
        const userId = req.user.id;
        const { requestId, action } = req.body;
        
        if (!requestId || !action) {
            return errorResponse(res, '缺少必要参数', 400);
        }
        
        if (!['accept', 'reject'].includes(action)) {
            return errorResponse(res, '无效的操作', 400);
        }
        
        // 验证请求是否属于当前用户
        const [requests] = await db.execute(
            'SELECT * FROM friendships WHERE id = ? AND friend_id = ?',
            [requestId, userId]
        );
        
        if (requests.length === 0) {
            return errorResponse(res, '好友请求不存在', 404);
        }
        
        const status = action === 'accept' ? 'accepted' : 'rejected';
        
        await db.execute(
            'UPDATE friendships SET status = ?, accepted_at = NOW() WHERE id = ?',
            [status, requestId]
        );
        
        return successResponse(res, null, action === 'accept' ? '已接受好友请求' : '已拒绝好友请求');
        
    } catch (error) {
        console.error('处理好友请求错误:', error);
        return errorResponse(res, '处理好友请求失败', 500, error);
    }
};

module.exports = {
    getLeaderboard,
    getUserRank,
    searchUsers,
    addFriend,
    getFriendsList,
    getFriendRequests,
    handleFriendRequest
};

